﻿using DtuService;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetCommand;
using SuperSocket.SocketBase;
using NetCommand.Web;

namespace DtuService
{
    public class HtmPage : IPageProcess
    {
        public string Token;
        protected HttpClient httpClient;
        public Session _Session;
        public virtual void ProcessPage(HttpClient http, string htm, params string[] message)
        {
            httpClient = http;
            // token 验证， 判断是否需要重新登录
            string decodeMsg = System.Web.HttpUtility.UrlDecode(message[0], System.Text.Encoding.GetEncoding("gb2312"));
            WebMessage msg = deserializeMessage(decodeMsg);
            if (msg == null)
            {
                http.NotImplemented();
                return;
            }
            if (msg.CLSID == WebMessageDefine.id_LoginMessage)
            {
                OnPageProcess(msg);
            }
            else if (ServerMain.GetServer<CacheServer>().TokenIsLegal(msg.Token))
            {
                Token = msg.Token;
                OnPageProcess(msg);
            }
            else
            { // 重新登录
                sendOkResponse(Encoding.UTF8.GetBytes(serializeMessage(new ReLogin())));
            }
        }

        protected uint userID
        {
            get
            {
                TokenInfo token = ServerMain.GetServer<CacheServer>().GetTokenInfo(Token);
                if ( token != null)
                {
                    return token.userID;
                }
                return 0;
            }
        }

        public virtual void OnPageProcess(WebMessage msg)
        {

        }

        protected virtual void sendResponse(byte[] bContent, string responseCode,
                                  string contentType)
        {
            httpClient.SendResponse(bContent, responseCode, contentType);
        }

        protected virtual void sendOkResponse(byte[] bContent)
        {
            httpClient.SendOkResponse(bContent, HttpContentType.HTML);
        }

        protected string serializeMessage(WebMessage msg)
        {
            return WebMessageFactory.SerializeMessage(msg);
        }

        /*
         * Message
         */
        protected WebMessage deserializeMessage(string message)
        {
            return WebMessageFactory.DeserializeMessage(message);
        }
    }
}
